/*
 * @Author: zhangfeng
 * @Date: 2023-12-13 18:22:53
 * @LastEditTime: 2024-01-09 16:28:45
 * @LastEditors: zhangfeng
 * @Description: 菜单模型
 * @FilePath: \nodeapi\src\server\menus.server.js
 * © 2023 张峰，All rights reserved.
 */
const Menus = require("../model/menu.model");
const { Op, where } = require("sequelize");
class MenusServer {
  // 创建菜单
  async createMenus(menus) {
    const res = await Menus.create(menus);
    return res.dataValues;
  }
  // 获取菜单
  async findMenus(pageNum, pageSize) {
    const { count, rows } = await Menus.findAndCountAll({
      order: [["orderNum", "ASC"]],
    });
    return {
      pageNum,
      pageSize,
      total: count,
      list: rows,
    };
  }
  // 修改菜单
  async updateMenus({
    id,
    parentId,
    shown,
    orderNum,
    operatorId,
    components,
    premi,
    path,
    name,
    level,
    icon,
    href,
    updatedBy,
    updatedTime,
    description,
  }) {
    const whereOpt = { id };
    const newMenus = {};
    if (parentId !== undefined && parentId !== null) {
      Object.assign(newMenus, { parentId: parentId });
    }
    components && Object.assign(newMenus, { components });
    premi && Object.assign(newMenus, { premi });
    path && Object.assign(newMenus, { path });
    Object.assign(newMenus, { shown });
    orderNum && Object.assign(newMenus, { orderNum });
    operatorId && Object.assign(newMenus, { operatorId });
    name && Object.assign(newMenus, { name });
    level && Object.assign(newMenus, { level });
    icon && Object.assign(newMenus, { icon });
    href && Object.assign(newMenus, { href });
    updatedBy && Object.assign(newMenus, { updatedBy });
    updatedTime && Object.assign(newMenus, { updatedTime });
    description && Object.assign(newMenus, { description });
    const res = await Menus.update(newMenus, {
      where: whereOpt,
    });
    return res[0] > 0;
  }
  // 删除菜单
  async deleteserverMenus(id) {
    const res = await Menus.destroy({
      where: {
        id: id,
      },
    });
    return res;
  }
  // 是否有子元素
  async isHasChildServerMenus(id) {
    const res = await Menus.findAll({
      where: {
        parentId: id,
      },
    });
    return res.length > 0 ? true : false;
  }

  // 根据菜单id查询菜单
  async getMenusById(menusId) {
    let whereOpt = {};
    if (Array.isArray(menusId)) {
      whereOpt = {
        id: {
          [Op.in]: menusId,
        },
      };
    } else {
      whereOpt = {
        id: menusId,
      };
    }
    const result = await Menus.findAll({
      where: whereOpt,
    });
    return result;
  }
}

module.exports = new MenusServer();
